<template>
    <div class="user">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 搜索框 -->
        <div style="margin-top: 15px;">
            <el-input placeholder="请输入内容"  class="input-with-select" style="width:300px;" v-model="searchData">
                <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
            </el-input>
            <el-button type="success" plain @click="addTable=true" >添加用户</el-button>
        </div>
        <!-- 用户列表---table -->
        <template>
            <el-table :data="userLists" stripe style="width: 100%">
                <el-table-column type="index" width="50"> </el-table-column>
                <el-table-column prop="username" label="姓名" >
                </el-table-column>
                <el-table-column prop="email" label="邮箱" width="180">
                </el-table-column>
                <el-table-column prop="mobile" label="电话">
                </el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="setUserType(scope.row)" active-color="#13ce66"  inactive-color="#ff4949"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                             <el-button type="success" icon="el-icon-edit" @click="editUser(scope.row),dialogVisible = true" plain></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="top">
                            <el-button type="success" icon="el-icon-delete" @click="delUser(scope.row)" plain></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="权限分配" placement="top">
                            <el-button type="success" icon="el-icon-check" @click="roleUser(scope.row),powerDialog=true" plain></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </template>
        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4" :page-sizes="[1, 2, 3, 4]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
        <!-- 模态框----添加 -->
        <el-dialog title="添加" :visible.sync="addTable" width="30%" :before-close="handleClose">
            <el-form :label-position="labelPosition" label-width="80px" :model="addUserData" ref="addUserData" :rules="rules">
                <el-form-item label="姓名" prop="username">
                    <el-input v-model="addUserData.username" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <!-- <el-form-item label="用户角色" prop="role">
                    <el-radio v-model="addUserData.role" label="超级管理员">超级管理员</el-radio>
                    <el-radio v-model="addUserData.role" label="普通管理员">普通管理员</el-radio>
                    <el-radio v-model="addUserData.role" label="用户">用户</el-radio>
                    <el-radio v-model="addUserData.role" label="测试">测试</el-radio>
                </el-form-item> -->
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserData.email" type="email" placeholder="请输入正确的电子邮箱(可不填)"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="addUserData.mobile" placeholder="请输入正确的手机号码(可不填)"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUserData.password" type="password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="pwd_again">
                    <el-input v-model="addUserData.pwd_again" type="password" placeholder="请再次输入密码"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addUser('addUserData')" >添加用户</el-button>
                </el-form-item>
            </el-form>
            
        </el-dialog>
        <!-- 模态框----编辑 -->
        <el-dialog title="编辑" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <el-form :label-position="labelPosition" label-width="80px" :model="editUserData" ref="editUserData">
                <el-form-item label="姓名">
                    <el-input v-model="editUserData.username" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="用户角色">
                    <el-input v-model="editUserData.role" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="editUserData.email"></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="editUserData.mobile"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" center @click="PreEditUser('editUserData')">保存</el-button>
                </el-form-item>
            </el-form>
            
        </el-dialog>
        <!-- 模态框----角色分配 -->
        <el-dialog title="角色分配" :visible.sync="powerDialog" width="34%" :before-close="handleClose">
            <el-form :label-position="labelPosition" label-width="80px" :model="userPower" ref="userPower">
                <el-form-item label="用户名:">
                  <el-input v-model="userPower.username" disabled ></el-input>
                </el-form-item>

                <el-form-item label="用户角色">
                    <el-radio-group v-model="userPower.rid">
                      <el-radio v-for="value in roleList" :key="value.id" :label="value.id" >{{value.roleName}}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" center @click="selectPower('userPower')">保存</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>


<script>
import {
  getUserLists,
  addUser,
  delUserData,
  editUser,
  roleName,
  getRole,
  userType
} from "@/api/index.js";
export default {
  data() {
    return {
      //用户列表动态展示数组
      userLists: [],
      value1: true,
      pagesize: 4,
      total: 1,
      pagenum: 1,
      currentPage4: 1,
      searchData: "",
      addFormVisible: false,
      dialogVisible: false,
      powerDialog: false,
      addTable: false,
      //角色分配
      roleList: [],
      userPower: {
        username: "",
        id: "",
        rid: 1
      },
      delID: 1,
      //表单对齐方式
      labelPosition: "left",
      //编辑数据
      editUserData: {
        username: "",
        email: "",
        mobile: "",
        role: "",
        id: ""
      },
      //角色分配数据

      //添加数据
      addUserData: {
        username: "",
        email: "",
        mobile: "",
        pwd_again: "",
        password: ""
      },
      //添加是的表单验证数据
      rules: {
        username: [
          { required: true, message: "请输入你的名字", trigger: "blur" }
        ],
        pwd_again: [
          { required: true, message: "请再次输入密码", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.updateUserList();
  },
  methods: {
    //弹出框关闭
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    //编辑
    editUser(row) {
      console.log(row);
      this.editUserData.username = row.username;
      this.editUserData.email = row.email;
      this.editUserData.mobile = row.mobile;
      this.editUserData.role = row.role_name;
      this.editUserData.id = row.id;
    },
    //保存修改
    PreEditUser(formname) {
      this.$refs[formname].validate(valid => {
        if (valid) {
          console.log(this.editUserData.id);

          editUser(this.editUserData.id, this.editUserData).then(res => {
            // console.log(res);
            if (res.meta.status == 200) {
              console.log(res);
              this.$message({
                message: res.meta.msg,
                type: "success"
              });
              //更新
              this.updateUserList();
              //关闭dialog
              this.dialogVisible = false;
            }
          });
        }
      });
    },
    //删除
    delUser(row) {
      // console.log(row);
      this.delID = row.id;
      this.$confirm("是否删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delUserData(this.delID).then(res => {
            // console.log(res);
            this.$message({
              type: "success",
              message: "删除成功"
            });
            this.updateUserList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //权限分配
    //获取角色列表
    roleUser(row) {
      // console.log(row,'row');

      this.userPower.username = row.username;
      this.userPower.id = row.id;
      this.userPower.role_name = row.role_name;
      this.roleList = true;
      console.log(this.userPower, "userPower");
      getRole().then(res => {
        console.log(res);
        this.roleList = res.data;
        // console.log(this.roleList,'role')
      });
    },
    selectPower() {
      console.log(this.userPower);
      roleName(this.userPower).then(res => {
        console.log(res);
        //关闭弹窗
        this.powerDialog = false;
        //提示
        this.$message({
          message: res.meta.msg,
          type: "success"
        });
      });
    },
    setUserType(row) {
      console.log(row);
      userType(row).then(res => {
        if (res.meta.status === 200) {
          this.$message({
            message: res.meta.msg,
            type: "success"
          })
          this.updateUserList()
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },
    //搜索功能
    search() {
      this.updateUserList();
    },
    //分页
    handleSizeChange(val) {
      this.pagesize = val;
      this.updateUserList();
    },
    //分页跳转
    handleCurrentChange(val) {
      this.pagenum = val;
      this.updateUserList();
    },
    //添加用户
    addUser(formname) {
      if (this.addUserData.username.trim() == "") {
        this.$notify({
          title: "提示",
          message: "姓名不能为空",
          duration: 2000
        });
        return;
      } else if (this.addUserData.pwd_again.trim() == "") {
        this.$notify({
          title: "提示",
          message: "确认密码不能为空",
          duration: 2000
        });
        return;
      } else if (this.addUserData.password.trim() == "") {
        this.$notify({
          title: "提示",
          message: "密码不能为空",
          duration: 2000
        });
        return;
      } else if (this.addUserData.password != this.addUserData.pwd_again) {
        this.$notify({
          title: "提示",
          message: "两次输入的密码不一致,请重试",
          duration: 2000
        });
        return;
      } else {
        console.log(this.addUserData);
        this.addFormVisible = false;
        this.$refs[formname].validate(valid => {
          if (valid) {
            addUser(this.addUserData).then(res => {
              if (res.meta.status == 201) {
                console.log(res);
                this.$message({
                  message: res.meta.msg,
                  type: "success"
                });
                //更新
                this.updateUserList();
                //关闭dialog
                this.addTable = false;
                //清空
                this.$refs[formname].resetFields();
              } else {
                this.$message({
                  message: res.meta.msg,
                  type: "error"
                });
                this.addTable = false;
              }
            });
          }
        });
      }
    },
    //更新表单
    updateUserList() {
      getUserLists({
        query: this.searchData,
        pagenum: this.pagenum,
        pagesize: this.pagesize
      }).then(res => {
        console.log(res);
        this.userLists = res.data.users;
        this.total = res.data.total;
      });
    },
    
  }
};
</script>




<style  scoped>
.el-pagination {
  /* display: block; */
  margin-top: 50px;
  text-align: center;
}
.el-radio {
  margin-bottom: 10px;
}
</style>
